import axios from "axios";
import qs from "qs";
import router from "../router/index";
// axios二次封装插件
// 1 请求头的配置
// 2. 请求拦截器
// 3  响应拦截器
// 4 promise 返回请求对象
// 5.开发模式 和生产模式的 baseUrl 不同
// 6、http://192.178.1.188:8080

var serivce = axios.create({
    baseURL: process.env.NODE_ENV == "production" ?
        "http://192.178.1.188:8080" :
        "https://apipc-xiaotuxian-front.itheima.net",
    timeout: 5000,
});

export default function request(url, method = "get", data, header) {
    if (method == "post") {
        if (header == "json") {
            serivce.defaults.headers.post["Content-type"] =
                "application/json;charset=UTF-8";
        } else if (header == "mul") {
            serivce.defaults.headers.post["Content-type"] = "multipart/form-data";
        }
    }

    // 请求拦截器
    serivce.interceptors.request.use((config) => {
        // 获取token 携带到请求头
        if (localStorage.token) {
            console.log(localStorage.token);
            config.headers.Authorization = `Bearer ${localStorage.token}`;
        }

        return config;
    });

    // 响应拦截器
    serivce.interceptors.response.use(
        (response) => {
            return response;
        },
        (err) => {
            console.log(err);
            if (err.response.data.code == "10017") {
                alert("账号或密码错误");
            }
            if (err.response && err.response.status === 401) {
                router.push("/login");
            }
        }
    );

    return new Promise((resolve, reject) => {
        serivce({
                url: url,
                method: method,
                [method == "get" ? "params" : "data"]: data,
            })
            .then((res) => {
                resolve(res);
            })
            .catch((err) => {
                reject(err);
            });
    });
}